﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using BL.Service;
using BL.Entity;

namespace LTO
{
    /// <summary>
    /// Interaction logic for Export_ImportData.xaml
    /// </summary>
    public partial class Export_ImportData : Window
    {
        tbl_NumberServer service = new tbl_NumberServer();
        List<NumberDTO> dbNUmber;
        public Export_ImportData()
        {
            InitializeComponent();
            List<NumberTypeDTO> numType = new List<NumberTypeDTO>();
           

            numType.Add(new NumberTypeDTO() { Name="3 บน", value="O3" });
            numType.Add(new NumberTypeDTO() { Name="3 ล่าง" ,value="U3" });
            numType.Add(new NumberTypeDTO() { Name="โต๊ด 3 บน" ,value="T3" });
            numType.Add(new NumberTypeDTO() { Name="2 บน", value="O2" });
            numType.Add(new NumberTypeDTO() { Name="2 ล่าง" ,value="U2" });
            numType.Add(new NumberTypeDTO() { Name="โต๊ด 2 บน", value="T2" });
            numType.Add(new NumberTypeDTO() { Name="2 บนคู่หน้า", value="TF" });
            numType.Add(new NumberTypeDTO() { Name="2 บนคู่ถ่าง", value="TS" });
            numType.Add(new NumberTypeDTO() { Name="วิ่งบน", value="O1" });
            numType.Add(new NumberTypeDTO() { Name="วิ่งล่าง", value="U1" });
            numType.Add(new NumberTypeDTO() { Name="โต๊ดหมู่", value="FN" });
        
          

        }
        public string GetXMLFromObject(object o)
        {
            XmlSerializer XmlS = new XmlSerializer(o.GetType());

            StringWriter sw = new StringWriter();
            XmlTextWriter tw = new XmlTextWriter(sw);



            XmlS.Serialize(tw, o);
            return sw.ToString();
        }
        protected T FromXml<T>(String xml)
        {
            T returnedXmlClass = default(T);

            try
            {
                using (TextReader reader = new StringReader(xml))
                {
                    try
                    {
                        returnedXmlClass = (T)new XmlSerializer(typeof(T)).Deserialize(reader);
                    }
                    catch (InvalidOperationException)
                    {
                        // String passed is not XML, simply return defaultXmlClass
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return returnedXmlClass;
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                List<NumberDTO> ReadNUmber = new List<NumberDTO>();
                // Create OpenFileDialog
                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

                // Set filter for file extension and default file extension
                dlg.DefaultExt = ".xml";
                dlg.Filter = "Xml documents (.xml)|*.xml";

                // Display OpenFileDialog by calling ShowDialog method
             //   Nullable<bool> result = dlg.ShowDialog();

                // Get the selected file name and display in a TextBox
               // if (result == true)
               // {
                    // Open document

                    string filename = System.Configuration.ConfigurationManager.AppSettings["ImportPath"];
                    
                    string line = "";
                    string resultXML = "";
                    StreamReader sr = File.OpenText(filename);
                    while ((line = sr.ReadLine()) != null)
                    {
                        resultXML += line;
                    }
                    ReadNUmber = FromXml<List<NumberDTO>>(resultXML);
                    dataGrid1.ItemsSource = ReadNUmber;
                    btnImport.IsEnabled = true;
                    btnExport.IsEnabled = false;
                    btnImport.Content = string.Format("นำเข้าข้อมูล : {0} แถว", ReadNUmber.Count);
                    MessageBox.Show("อ่านไฟล์เรียบร้อย ", "ReadFile Information", MessageBoxButton.OK, MessageBoxImage.Information);


                //}
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "Error Open File", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            string xmlObj = GetXMLFromObject(dbNUmber);
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "ExportData"; // Default file name
            dlg.DefaultExt = ".xml"; // Default file extension
            dlg.Filter = "xml documents (.xml)|*.xml"; // Filter files by extension

            // Show save file dialog box
        //    Nullable<bool> result = dlg.ShowDialog();

            // Process save file dialog box results
          //  if (result == true)
          //  {
                // Save document
               
           // }
            string filename = System.Configuration.ConfigurationManager.AppSettings["ExportPath"];
            File.WriteAllText(filename, xmlObj);
            MessageBox.Show(string.Format("ส่งออกไฟล์เรียบร้อย {0} ", filename), "Export Information", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            dbNUmber = new List<NumberDTO>();


            dbNUmber = service.getAllnumber(chkOver.IsChecked.Value);
            dataGrid1.ItemsSource = dbNUmber;
            btnExport.IsEnabled = true;
            btnImport.IsEnabled = false;
            btnExport.Content = string.Format("ส่งออกข้อมูล : {0} แถว", dbNUmber.Count);
            MessageBox.Show("โหลดข้อมูลเรียบร้อย ", "LoadData Information", MessageBoxButton.OK, MessageBoxImage.Information);

        }

        private void btnImport_Click(object sender, RoutedEventArgs e)
        {
            if (dbNUmber != null && dbNUmber.Count > 0)
            {
                int result = 0;
              result=  service.ImportFile(dbNUmber,Gobalsource.UserNameLogin);
              MessageBox.Show(string.Format("นำเข้าไฟล์ เรียนร้อย {0} Record", result), "Import Information", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
    }
}
